﻿Imports AjaxControlToolkit

Public Class OutletReview
    Inherits System.Web.UI.Page
    Private checkFollowShop As Boolean
    Public outletID As Integer
    Public dbmanager As DBManager = New DBManager


    'This constant is to alternate between ascending and descending sort orders for the reviews listview
    'when diffSort is false, it means that the same sort by type has been clicked twice or more in a row
    Private Shared diffSort As Boolean

    'To set masterpage 
    Protected Sub Page_PreInit(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreInit

        'Check if user is null
        If (Session("user") IsNot Nothing) Then
            'Retrieve userAcc details from session
            Dim userLoggedIn As userAcc = Session("user")
            'Check if user is admin, assign masterpage respectively
            If userLoggedIn.isAdmin Then
                Me.MasterPageFile = "~/MasterPage/Admin.Master"
            Else
                Me.MasterPageFile = "~/MasterPage/User.Master"
            End If
        Else
            'For anonymous users
            Me.MasterPageFile = "~/MasterPage/User.Master"
            'Enable this line to prevent anonymous users from entering this page
            ' Response.Redirect("~/Login.aspx")
        End If
    End Sub

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Try
            If (Request.QueryString("id") IsNot Nothing) Then
                outletID = Request.QueryString("id")
                If outletID = 0 Then
                    Response.Redirect("home.aspx")
                End If
            Else
                Response.Redirect("home.aspx")
            End If
        Catch ex As Exception
        End Try
        If Not dbmanager.checkOutletExist(outletID) Then
            Response.Redirect("home.aspx")
        End If

        'Set up recommendations
        Dim recommended As ArrayList = dbmanager.recommendOutlets(outletID)
        hlOutletRec1.NavigateUrl = "OutletReview.aspx?id=" + recommended(0).ToString()
        hlOutletRec2.NavigateUrl = "OutletReview.aspx?id=" + recommended(1).ToString()
        hlOutletRec3.NavigateUrl = "OutletReview.aspx?id=" + recommended(2).ToString()

        hlOutletRec1.Text = dbmanager.getOutletDetails(Convert.ToInt32(recommended(0).ToString()))(0)
        hlOutletRec2.Text = dbmanager.getOutletDetails(Convert.ToInt32(recommended(1).ToString()))(0)
        hlOutletRec3.Text = dbmanager.getOutletDetails(Convert.ToInt32(recommended(2).ToString()))(0)

        ibRec1.ImageUrl = "IHttpHandler.ashx?id=" + dbmanager.getOutletImage(Convert.ToInt32(recommended(0).ToString())).ToString()
        ibRec2.ImageUrl = "IHttpHandler.ashx?id=" + dbmanager.getOutletImage(Convert.ToInt32(recommended(1).ToString())).ToString()
        ibRec3.ImageUrl = "IHttpHandler.ashx?id=" + dbmanager.getOutletImage(Convert.ToInt32(recommended(2).ToString())).ToString()

        ibRec1.PostBackUrl = "OutletReview.aspx?id=" + recommended(0).ToString()
        ibRec2.PostBackUrl = "OutletReview.aspx?id=" + recommended(1).ToString()
        ibRec3.PostBackUrl = "OutletReview.aspx?id=" + recommended(2).ToString()

        'For follow shop
        Dim userLoggedin As userAcc = Session("user")
        If (Session("user") IsNot Nothing) Then
            'Retrieve userID  from session
            userLoggedin = Session("user")
            hfUser.Value = userLoggedin.userID
            checkFollowShop = dbmanager.checkFollowShop(outletID, hfUser.Value)
            If checkFollowShop = False Then
                btnAddThisBranch.Enabled = False
                btnAddThisBranch.ToolTip = "You have already followed this shop."

            Else
                'enable the add this outlet btn
                btnAddThisBranch.Enabled = True
                btnAddThisBranch.ToolTip = "Click here to follow this branch"
            End If
        Else
            ' set the userID as 0
            hfUser.Value = 0
            'disable the add this outlet btn
            btnAddThisBranch.Enabled = False
            btnAddThisBranch.ToolTip = "Please Login to follow this branch"
        End If


        'Check if there is a report 
        If (Session("ReportID") IsNot Nothing) Then
            'Check that reportID is not 0 and that user is admin
            If (Not Session("ReportID") = 0) And Me.MasterPageFile = "/MasterPage/Admin.Master" Then
                Dim reportData = dbmanager.retrieveReportDetails(Convert.ToInt32(Session("ReportID").ToString()))
                Dim type As String = reportData(0)
                Dim ID As Integer = Convert.ToInt32(reportData(2))
                lblAdminUpdateTitle.Text = type
                Dim myHTMLlink As HtmlLink = New HtmlLink
                myHTMLlink.Href = "~/Styles/dynamic.css"
                myHTMLlink.Attributes.Add("rel", "stylesheet")
                myHTMLlink.Attributes.Add("type", "text/css")
                Page.Header.Controls.Add(myHTMLlink)
                Select Case type
                    Case "report review"
                        pnlAdminUpdate.Visible = True
                        If dbmanager.getOutletIDFromReview(ID) = (Convert.ToInt32(outletID)) Then
                            pnlAdminUpdate.Visible = True
                            tbxAdminUpdateComments.Text = reportData(1)
                            btnDeleteOutlet.Visible = False
                            btnDeleteBusiness.Visible = False
                            btnResolved.Visible = True
                        End If

                    Case "report comment"
                        pnlAdminUpdate.Visible = True
                        If dbmanager.getOutletIDFromComment(ID) = (Convert.ToInt32(outletID)) Then
                            pnlAdminUpdate.Visible = True
                            tbxAdminUpdateComments.Text = reportData(1)
                            btnDeleteOutlet.Visible = False
                            btnDeleteBusiness.Visible = False
                            btnResolved.Visible = True
                        End If

                    Case "Proposed Deletion of Business"
                        pnlAdminUpdate.Visible = True
                        If dbmanager.getBusinessID(Convert.ToInt32(outletID)) = ID Then
                            pnlAdminUpdate.Visible = True
                            tbxAdminUpdateComments.Text = reportData(1)
                            btnDeleteOutlet.Visible = False
                            btnDeleteBusiness.Visible = True
                            btnResolved.Visible = True
                        End If
                    Case "Proposed Deletion of Outlets"
                        If Convert.ToInt32(outletID) = ID Then
                            pnlAdminUpdate.Visible = True
                            tbxAdminUpdateComments.Text = reportData(1)
                            btnDeleteOutlet.Visible = True
                            btnDeleteBusiness.Visible = False
                            btnResolved.Visible = True
                        End If

                End Select

            End If
        End If

        'Update the chart with latest values
        updateChartValues()

        'Populate outlet information
        populateOutlet()
        'Populate outletList
        populateOutletList()
        'Populate business information
        populateBusiness()
        'Business name - outlet name
        Dim combinedName = dbmanager.getBusinessOutletName(outletID)
        'Set page title
        Page.Title = combinedName

        'Set label for reviews
        lblCombined.Text = dbmanager.getNumReviews(outletID).ToString + " reviews for " + combinedName
        lblCombinedNew.Text = combinedName

        'Set twitter share text
        hfTwitterText.Value = "Try this! : " + combinedName + " " + Request.Url.ToString()

        'Set postbackurl for editting
        lbEditBusiness.PostBackUrl = "ProposeReport.aspx?id=b" + dbmanager.getBusinessID(outletID).ToString
        lbEditOutlet.PostBackUrl = "ProposeReport.aspx?id=o" + outletID.ToString

        If (Not Page.IsPostBack) Then
            'Set sort up/down images to be not visible
            imgDateAsc.Visible = False
            imgDateDesc.Visible = False
            imgHelpfulAsc.Visible = False
            imgHelpfulDesc.Visible = False
            imgRatingAsc.Visible = False
            imgRatingDesc.Visible = False
        End If

        'To enable/disable add review and follow button depending on whether user is logged in
        If (Session("user") IsNot Nothing) Then
            'Enable add review button
            btnNewReview.Enabled = True
            btnNewReview.ToolTip = "Click to write a new review for this branch"

        Else

            'Disable new reviews
            btnNewReview.Enabled = False
            btnNewReview.ToolTip = "Please login to add review"

        End If

    End Sub

    Protected Sub btnSubmitComment_Click(ByVal sender As Object, ByVal e As System.EventArgs)

    End Sub

    'Populate the dropdownlist with all the branches belonging to the company 
    Protected Sub populateOutletList()

        Dim itemList = dbmanager.getListOutlets(outletID)
        For Each outlet As ListItem In itemList
            ddlOutlets.Items.Add(outlet)
        Next
        ddlOutlets.SelectedValue = outletID

    End Sub

    'Populate company details
    Protected Sub populateBusiness()
        Dim businessData = dbmanager.getBusinessDetails(outletID)
        lblBusinessName.Text = businessData(0)
        lblCategory.Text = businessData(1)
        lbWebsite.PostBackUrl = businessData(2)
        'If longer than 36 characters, we substring it to prevent overflow, try to get first 36 characters, if nullpointerexception, display full link
        'Try
        '    lbWebsite.Text = businessData(2).ToString.Substring(0, 35) + "..."
        'Catch ex As Exception
        '    lbWebsite.Text = businessData(2)
        'End Try

        tbxDetails.Text = businessData(3)
        Dim imageID = dbmanager.getOutletImage(outletID)
        If Not imageID = 0 Then
            imgBusiness.ImageUrl = ("IHttpHandler.ashx?id=" + imageID.ToString)
        End If


    End Sub

    'Populate branch details
    Protected Sub populateOutlet()
        Dim outletData = dbmanager.getOutletDetails(outletID)
        lblAddress.Text = outletData(1)
        lblOpeningHrs.Text = outletData(2)
        tbxRemarks.Text = outletData(3)
        lblTelNo.Text = outletData(4)


    End Sub

    'Updates the chart with values from the database
    Protected Sub updateChartValues()
        Dim dataValues = dbmanager.getChartData(outletID)
        hfQuality.Value = dataValues(0)
        hfValue.Value = dataValues(1)
        hfService.Value = dataValues(2)
        hfOverall.Value = dataValues(3)
        Dim overallRating = dbmanager.getOverallRating(outletID)
        If (overallRating > 0) Then
            Dim length = overallRating.ToString.Length
            If length > 5 Then
                lblRating.Text = "Overall Rating : " + overallRating.ToString().Substring(0, 4)
            Else
                lblRating.Text = "Overall Rating : " + overallRating.ToString()
            End If
        Else
            lblRating.Text = "No ratings available"
        End If

        Dim dataValuesDetail = dbmanager.getDistriChartData(outletID)
        hfDetailChart1.Value = dataValuesDetail(0)
        hfDetailChart2.Value = dataValuesDetail(1)
        hfDetailChart3.Value = dataValuesDetail(2)
        hfDetailChart4.Value = dataValuesDetail(3)
        hfDetailChart5.Value = dataValuesDetail(4)

    End Sub

    'For formatting each item as it is databound in the listview for reviews
    Protected Sub lvComments_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.ListViewItemEventArgs)

        Dim lblUserID As Label = e.Item.FindControl("user_IDLabel")
        Dim btnDelete As LinkButton = e.Item.FindControl("lbDeleteComment")
        Dim idLabelComments As Label = e.Item.FindControl("idLabelComments")

        Dim commenterUserID = lblUserID.Text
        Try
            If (Session("ReportID") IsNot Nothing And Me.Session("user").isAdmin) Then
                Dim reportID = Session("ReportID")
                Dim reportData = dbmanager.retrieveReportDetails(reportID)
                Dim type As String = reportData(0)
                If type = "report comment" Then
                    idLabelComments.Visible = True
                End If
            End If

            If (commenterUserID = Me.Session("user").userID) Or Me.Session("user").isAdmin Then
                btnDelete.Visible = True
            Else
                btnDelete.Visible = False
            End If
        Catch ex As Exception
            'If user is not logged in
            btnDelete.Visible = False
        End Try


    End Sub

    'For formatting each item as it is databound in the listview for reviews
    Protected Sub ListView1_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.ListViewItemEventArgs) Handles lvReview.ItemDataBound

        Dim idLabel As Label = e.Item.FindControl("idLabel")

        'To set colour of the helpfulness label based on whether it is negative or positive
        Dim labelHelp As Label = e.Item.FindControl("helpfulnessLabel")
        Dim tempString As String = labelHelp.Text
        If tempString = "0" Then
            'if 0, black
            labelHelp.ForeColor = Drawing.Color.Black
        ElseIf tempString.Contains("-") Then
            'If negative, red
            labelHelp.ForeColor = System.Drawing.Color.Red

        Else
            'If positive , green
            labelHelp.ForeColor = System.Drawing.Color.Green
        End If
        'To set the star ratings
        'get all the numerical ratings from 1-5
        Dim ratingQuality As Label = e.Item.FindControl("rating_qualityLabel")
        Dim ratingValue As Label = e.Item.FindControl("rating_valueLabel")
        Dim ratingServices As Label = e.Item.FindControl("rating_serviceLabel")
        Dim ratingOverall As Label = e.Item.FindControl("rating_overallLabel")

        'get all the numerical ratings and multiply by 20
        ' 1 = 20% , 2 = 40% , 3 = 60% , 4 = 80% , 5 = 100%
        Dim ratingQualityValue = Convert.ToInt32(ratingQuality.Text.ToString()) * 20
        Dim ratingValueValue = Convert.ToInt32(ratingValue.Text.ToString()) * 20
        Dim ratingServiceValue = Convert.ToInt32(ratingServices.Text.ToString()) * 20
        Dim ratingOverallValue = Convert.ToDouble(ratingOverall.Text.ToString()) * 20

        'Try to get profile pictures of the reviewer
        Dim lblUserID As Label = e.Item.FindControl("user_IDLabel")
        Dim reviwerUserID = lblUserID.Text
        Dim profileImage As Image = e.Item.FindControl("imgProfile")
        Dim imageID = dbmanager.getUserImage(Convert.ToInt32(reviwerUserID))

        'Set default user image 
        If imageID = 0 Then
            imageID = 3
        End If
        profileImage.ImageUrl = "IHttpHandler.ashx?id=" + imageID.ToString

        'now to set all the div for the star rating system to display correctly
        Dim ratingQualityStar As System.Web.UI.HtmlControls.HtmlGenericControl = e.Item.FindControl("ratingQualityStar")
        ratingQualityStar.Attributes.Add("style", "width:" + ratingQualityValue.ToString() + "%")
        Dim ratingValueStar As System.Web.UI.HtmlControls.HtmlGenericControl = e.Item.FindControl("ratingValueStar")
        ratingValueStar.Attributes.Add("style", "width:" + ratingValueValue.ToString() + "%")
        Dim ratingServiceStar As System.Web.UI.HtmlControls.HtmlGenericControl = e.Item.FindControl("ratingServiceStar")
        ratingServiceStar.Attributes.Add("style", "width:" + ratingServiceValue.ToString() + "%")
        Dim ratingOverallStar As System.Web.UI.HtmlControls.HtmlGenericControl = e.Item.FindControl("ratingOverallStar")
        ratingOverallStar.Attributes.Add("style", "width:" + ratingOverallValue.ToString() + "%")

        ' To set if the delete button is visible, it will only be visible to review owner and admins
        Dim lbDelete As LinkButton = e.Item.FindControl("lbDelete")
        Try
            If (Me.Session("user").isAdmin And Session("ReportID") IsNot Nothing) Then
                Dim reportID = Session("ReportID")
                Dim reportData = dbmanager.retrieveReportDetails(reportID)
                Dim type As String = reportData(0)
                If type = "report review" Then
                    idLabel.Visible = True
                End If
            End If

            If (reviwerUserID = Me.Session("user").userID) Or Me.Session("user").isAdmin Then
                lbDelete.Visible = True
            Else
                lbDelete.Visible = False
            End If
        Catch ex As Exception
            lbDelete.Visible = False
        End Try

        Dim labelReviewID As Label = e.Item.FindControl("review_IDLabel")
        Dim reviewID As String = labelReviewID.Text

        'To configure the nested listview for comments
        Dim lvComments As ListView = e.Item.FindControl("lvComments")

        Dim objComments As SqlDataSource = e.Item.FindControl("SqlDataSourceComments")
        Dim parameter As Parameter = objComments.SelectParameters(0)
        parameter.DefaultValue = reviewID
        lvComments.DataSourceID = objComments.ID
        lvComments.DataBind()

        'Disable helpful rating button if user is not logged in 
        'Disable submit button if user is not logged in  
        Dim accordion As Accordion = e.Item.FindControl("accordionNewComment")
        Dim lbHelpfulYes As LinkButton = e.Item.FindControl("lbHelpfulYes")
        Dim lbHelpfulNo As LinkButton = e.Item.FindControl("lbHelpfulNo")

        Dim accordionCommentPane As AccordionPane = accordion.Panes(0)
        accordionCommentPane.Enabled = False
        Dim btnNewComment As Button = accordionCommentPane.FindControl("btnSubmitComment")
        Dim tbxNewComment As TextBox = accordionCommentPane.FindControl("tbxNewComment")
        Try
            If (Session("user") IsNot Nothing) Then
                accordionCommentPane.Enabled = True
                btnNewComment.ToolTip = "Submit new comment"
                tbxNewComment.ToolTip = ""
                lbHelpfulYes.Enabled = True
                lbHelpfulNo.Enabled = True
                lbHelpfulYes.ToolTip = "The review was helpful"
                lbHelpfulNo.ToolTip = "The review was not helpful"
            Else
                accordionCommentPane.Enabled = False
                btnNewComment.ToolTip = "Login to comment"
                tbxNewComment.ToolTip = "Login to comment"
                lbHelpfulYes.Enabled = False
                lbHelpfulNo.Enabled = False
                lbHelpfulYes.ToolTip = "Login to rate reviews"
                lbHelpfulNo.ToolTip = "Login to rate reviews"

            End If
        Catch ex As Exception

        End Try



    End Sub

    'For rating each review as helpful or not helpful
    Protected Sub ListView1_ItemCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.ListViewCommandEventArgs) Handles lvReview.ItemCommand
        Dim lblReviewID As Label = e.Item.FindControl("review_IDLabel")
        Dim reviewID = lblReviewID.Text
        Dim lblUserID As Label = e.Item.FindControl("user_IDLabel")
        Dim userID = lblUserID.Text
        Dim lblReviewerID As Label = e.Item.FindControl("reviewer_IDLabel")
        Dim reviewerID = lblReviewerID.Text
        Dim lblHelpfulness As Label = e.Item.FindControl("helpfulnessLabel")
        Dim helpfulness = Convert.ToInt32(lblHelpfulness.Text)
        Dim userLoggedIn As userAcc = Session("user")
        If (userLoggedIn.verified) Then

            Try
                Select Case e.CommandName

                    Case "helpfulYes"
                        If (
                        dbmanager.addReviewRate(reviewID, Me.Session("user").userID, 1)) Then
                            helpfulness = helpfulness + 1
                            dbmanager.updateReviewRating(reviewID, helpfulness)
                            lvReview.DataBind()
                        Else
                            MsgBox("Already rated this review", MsgBoxStyle.OkOnly, "Error")
                        End If

                    Case ("helpfulNo")

                        If (dbmanager.addReviewRate(reviewID, Me.Session("user").userID, -1)) Then
                            helpfulness = helpfulness - 1
                            dbmanager.updateReviewRating(reviewID, helpfulness)
                            lvReview.DataBind()
                        Else
                            MsgBox("Already rated this review", MsgBoxStyle.OkOnly, "Error")
                        End If
                    Case ("deleteReview")
                        If (MsgBox("Are you sure you want to delete this review?", MsgBoxStyle.OkCancel, "Delete Review") = MsgBoxResult.Ok) Then
                            dbmanager.deleteReview(reviewID)
                            lvReview.DataBind()
                            outletID = Request.QueryString("id")
                            'Business name - outlet name
                            Dim combinedName = dbmanager.getBusinessOutletName(outletID)
                            'Set label for reviews
                            lblCombined.Text = dbmanager.getNumReviews(outletID).ToString + " reviews for " + combinedName
                            lblCombinedNew.Text = combinedName
                            updateChartValues()
                        End If
                    Case ("deleteComment")
                        If (MsgBox("Are you sure you want to delete this review?", MsgBoxStyle.OkCancel, "Delete Comment") = MsgBoxResult.Ok) Then
                            Dim commentID = e.CommandArgument
                            dbmanager.deleteComment(commentID)
                            lvReview.DataBind()
                        End If
                    Case ("reportReview")
                        If (MsgBox("Report review as offensive or inappropriate ?", MsgBoxStyle.OkCancel, "Report review") = MsgBoxResult.Ok) Then
                            dbmanager.addReportDashboard(3, "report review", "Review reported as offensive                 Review ID : #RID" + reviewID.ToString(), reviewID, 0)
                        End If
                    Case ("reportComment")
                        If (MsgBox("Report comment as offensive or inappropriate ?", MsgBoxStyle.OkCancel, "Report comment") = MsgBoxResult.Ok) Then
                            Dim commentID = e.CommandArgument
                            dbmanager.addReportDashboard(3, "report comment", "Comment reported as offensive                 Comment ID: #CID" + commentID.ToString(), commentID, 0)
                        End If
                    Case ("newEmptyComment")
                        Dim x = 100
                    Case ("newComment")
                        Dim x = 100

                End Select


            Catch ex As Exception

            End Try
        Else
            MsgBox("Please verify your account before you are able to rate this review. Please check your email for the verification code")
        End If

    End Sub

    'New comment
    Protected Sub accordionComment_ItemCommand(ByVal sender As Object, ByVal e As AccordionCommandEventArgs)
        Try
            If e.CommandName = "newComment" Then
                'To get the accordion control
                Dim accordionParent As Accordion = e.Container.Parent.Parent
                'Using the ContentCssClass parameter to pass in the reviewID
                Dim combinedID = accordionParent.ContentCssClass
                Dim splitID = combinedID.Split("||")
                Dim user As userAcc = Session("user")
                Dim userID = user.userID
                Dim reviewID = splitID(2)

                Dim tbxCommentBody As TextBox = e.Container.FindControl("tbxNewCommentText")
                If tbxCommentBody.Text.Trim.Count > 0 Then
                    Dim comment = tbxCommentBody.Text
                    dbmanager.addReviewComment(reviewID, userID, comment)

                    tbxCommentBody.Text = ""
                    accordionParent.SelectedIndex = -1
                    lvReview.DataBind()
                End If

            End If

        Catch ex As Exception

        End Try

        'Dim x As UpdatePanel = e.Item.FindControl("updatePanelListview")
    End Sub

    'Toggle sort by date button
    Protected Sub lbSortDate_Click(ByVal sender As Object, ByVal e As EventArgs) Handles lbSortDate.Click
        'Toggle between asc and desc
        If (hfSort.Value = "date") Then
            If (diffSort = True) Then
                hfAscDesc.Value = "desc"
                imgDateDesc.Visible = True
                imgDateAsc.Visible = False
                imgHelpfulAsc.Visible = False
                imgHelpfulDesc.Visible = False
                imgRatingAsc.Visible = False
                imgRatingDesc.Visible = False
                diffSort = False
            Else
                hfAscDesc.Value = "asc"
                imgDateAsc.Visible = True
                imgDateDesc.Visible = False
                imgHelpfulAsc.Visible = False
                imgHelpfulDesc.Visible = False
                imgRatingAsc.Visible = False
                imgRatingDesc.Visible = False
                diffSort = True
            End If


        Else
            hfAscDesc.Value = "desc"
            imgDateDesc.Visible = True
            imgDateAsc.Visible = False
            imgHelpfulAsc.Visible = False
            imgHelpfulDesc.Visible = False
            imgRatingAsc.Visible = False
            imgRatingDesc.Visible = False
        End If

        'Set sort to be by date
        hfSort.Value = "date"
    End Sub

    'Toggle sort by rating button
    Protected Sub lbSortRating_Click(ByVal sender As Object, ByVal e As EventArgs) Handles lbSortRating.Click
        'Toggle between asc and desc
        If (hfSort.Value = "rating") Then
            If (diffSort = True) Then
                hfAscDesc.Value = "desc"
                imgRatingDesc.Visible = True
                imgDateAsc.Visible = False
                imgDateDesc.Visible = False
                imgHelpfulAsc.Visible = False
                imgHelpfulDesc.Visible = False
                imgRatingAsc.Visible = False
                diffSort = False
            Else
                hfAscDesc.Value = "asc"
                imgRatingAsc.Visible = True
                imgDateAsc.Visible = False
                imgDateDesc.Visible = False
                imgHelpfulAsc.Visible = False
                imgHelpfulDesc.Visible = False
                imgRatingDesc.Visible = False
                diffSort = True
            End If

        Else
            hfAscDesc.Value = "desc"
            imgRatingDesc.Visible = True
            imgDateAsc.Visible = False
            imgDateDesc.Visible = False
            imgHelpfulAsc.Visible = False
            imgHelpfulDesc.Visible = False
            imgRatingAsc.Visible = False
        End If

        'Set sort to be by rating
        hfSort.Value = "rating"

    End Sub

    'Toggle sort by helpfulness
    Protected Sub lbSortHelpful_Click(ByVal sender As Object, ByVal e As EventArgs) Handles lbSortHelpful.Click
        'Toggle between asc and desc
        If (hfSort.Value = "helpfulness") Then
            If (diffSort = True) Then
                hfAscDesc.Value = "desc"
                imgHelpfulDesc.Visible = True
                imgDateAsc.Visible = False
                imgDateDesc.Visible = False
                imgHelpfulAsc.Visible = False
                imgRatingAsc.Visible = False
                imgRatingDesc.Visible = False
                diffSort = False
            Else
                hfAscDesc.Value = "asc"
                imgHelpfulAsc.Visible = True
                imgDateAsc.Visible = False
                imgDateDesc.Visible = False
                imgHelpfulDesc.Visible = False
                imgRatingAsc.Visible = False
                imgRatingDesc.Visible = False
                diffSort = True
            End If

        Else
            hfAscDesc.Value = "desc"
            imgHelpfulDesc.Visible = True
            imgDateAsc.Visible = False
            imgDateDesc.Visible = False
            imgHelpfulAsc.Visible = False
            imgRatingAsc.Visible = False
            imgRatingDesc.Visible = False
        End If

        'Set sort to be by rating
        hfSort.Value = "helpfulness"

    End Sub

    'If user is not verified
    Protected Sub btnNewReview_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnNewReview.Click
        Dim userLoggedIn As userAcc = Session("user")
        If (userLoggedIn.verified) Then
            'To display the add review panel
            If (pnlAddReview.Visible = False) Then
                pnlAddReview.Visible = True
            End If
        Else
            MsgBox("Please verify your account before you are able to add new review. Please check your email for the verification code")
            btnNewReview.Visible = False

        End If
    End Sub

    'Clears data if cancel new review
    Protected Sub lbCancelNewReview_Click(ByVal sender As Object, ByVal e As EventArgs) Handles lbCancelNewReview.Click
        pnlAddReview.Visible = False
        tbxNewReviewTitle.Text = ""
        tbxReviewContent.Text = ""
        ratingQuality.CurrentRating = 2
        ratingService.CurrentRating = 2
        ratingValue.CurrentRating = 2
        rbVerdict1.Checked = False
        rbVerdict2.Checked = True
        rbVerdict3.Checked = False
    End Sub

    'Adding of new review
    Protected Sub btnNewReviewConfirm_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnNewReviewConfirm.Click
        Dim curUser As userAcc = Session("user")
        Dim verdict As String = ""
        If rbVerdict1.Checked Then
            verdict = "Cannot make it"
        ElseIf rbVerdict2.Checked Then
            verdict = "So-so only"
        Else
            verdict = "Good lah"
        End If
        Dim overallRating As Double = (ratingQuality.CurrentRating + ratingValue.CurrentRating + ratingService.CurrentRating) / 3
        If (dbmanager.addReview(outletID, curUser.userID, tbxNewReviewTitle.Text, ratingQuality.CurrentRating, ratingValue.CurrentRating, ratingService.CurrentRating, overallRating, verdict, tbxReviewContent.Text)) Then
            MsgBox("Thanks for your review !", MsgBoxStyle.OkOnly, "New Review")
            tbxNewReviewTitle.Text = ""
            tbxReviewContent.Text = ""
            ratingQuality.CurrentRating = 2
            ratingService.CurrentRating = 2
            ratingValue.CurrentRating = 2
            rbVerdict1.Checked = False
            rbVerdict2.Checked = True
            rbVerdict3.Checked = False
            lvReview.DataBind()
            outletID = Request.QueryString("id")
            'Business name - outlet name
            Dim combinedName = dbmanager.getBusinessOutletName(outletID)
            'Set label for reviews
            lblCombined.Text = dbmanager.getNumReviews(outletID).ToString + " reviews for " + combinedName
            lblCombinedNew.Text = combinedName
            updateChartValues()

        Else
            MsgBox("Error adding review", MsgBoxStyle.OkOnly, "New Review")
        End If
        pnlAddReview.Visible = False
        btnNewReview.Visible = True

    End Sub

    'Update outlet data based on selected item
    Protected Sub ddlOutlets_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs) Handles ddlOutlets.SelectedIndexChanged
        'Only if selected item is not "Select an outlet"
        If (Not ddlOutlets.SelectedValue = -1) Then
            outletID = ddlOutlets.SelectedValue
            'Update the chart with latest values
            updateChartValues()
            'Populate outlet information
            populateOutlet()
        End If

    End Sub

    'Add this branch to the followshop
    Protected Sub btnAddThisBranch_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnAddThisBranch.Click
        'Retrieve userID  from session
        Dim userLoggedIn As userAcc = Session("user")
        If (userLoggedIn.verified) Then
            hfUser.Value = userLoggedIn.userID
            'take the today as the date started
            Dim datestarted As Date
            datestarted = Today.Date
            'adding the shop to the list
            dbmanager.addFollowShop(outletID, hfUser.Value, datestarted)
            MsgBox("You have successfully followed this branch to the followed branch list", MsgBoxStyle.OkOnly, "Successfully followed this branch to the followed branch list")
            ListViewFollowedBranches.DataBind()
        Else
            MsgBox("Please verify your account before you are able to follow the branch. Please check your email for the verification code")
        End If

    End Sub

    'Delete this branch from followshop
    Protected Sub ListViewFollowedBranches_ItemCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.ListViewCommandEventArgs) Handles ListViewFollowedBranches.ItemCommand
        Try
            If e.CommandName = "deleteFollowShop" Then
                Dim userID As Integer = hfUser.Value
                Dim hfOutlet As HiddenField = e.Item.FindControl("hfOutlet")
                Dim outletIDFS As Integer = hfOutlet.Value
                dbmanager.deleteFollowShop(outletIDFS, userID)
                MsgBox("You have successfully deleted this branch from your followed branch list", MsgBoxStyle.OkOnly, "Successfully deleted this branch from your followed branch list")
                ListViewFollowedBranches.DataBind()
            End If

        Catch ex As Exception

        End Try

    End Sub

    'Resolves the report 
    Protected Sub btnResolved_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnResolved.Click
        'Check if there is a report 
        If (Session("ReportID") IsNot Nothing) Then
            Dim reportID = Session("ReportID")
            dbmanager.resolveReport(reportID)
            Session("ReportID") = Nothing
            Response.Redirect(Request.Path)
        End If
    End Sub

    'Delete business
    Protected Sub btnDeleteBusiness_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnDeleteBusiness.Click
        If (Session("ReportID") IsNot Nothing) Then
            Dim reportID = Session("ReportID")
            Dim reportData = dbmanager.retrieveReportDetails(reportID)
            Dim type As String = reportData(0)
            If type = "Proposed Deletion of Business" Then
                Dim ID As Integer = Convert.ToInt32(reportData(2))
                dbmanager.deleteBusinessDetails(ID)
                dbmanager.resolveReport(reportID)
                Response.Redirect("home.aspx")

            End If
        End If

    End Sub

    'Delete outlet
    Protected Sub btnDeleteOutlet_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnDeleteOutlet.Click
        If (Session("ReportID") IsNot Nothing) Then
            Dim reportID = Session("ReportID")
            Dim reportData = dbmanager.retrieveReportDetails(reportID)
            Dim type As String = reportData(0)
            If type = "Proposed Deletion of Outlets" Then

                Dim ID As Integer = Convert.ToInt32(reportData(2))
                If dbmanager.getNumOutlets(ID) = 1 Then
                    dbmanager.deleteBusinessDetails(dbmanager.getBusinessID(ID))
                Else
                    dbmanager.deleteOutletDetails(ID)
                End If

                dbmanager.resolveReport(reportID)
                Response.Redirect("home.aspx")
            End If
        End If
    End Sub

    Protected Sub sendEmail(ByVal verificationKey As String)
        Try
            Dim s As System.Net.Mail.SmtpClient = New System.Net.Mail.SmtpClient("smtp.gmail.com", 587)
            Dim nc As System.Net.NetworkCredential = New System.Net.NetworkCredential("goodanot@gmail.com", "threepotatoes")
            s.EnableSsl = True
            s.UseDefaultCredentials = False
            s.Credentials = nc

            s.Send("goodanot@gmail.com", "tbxEmail", "GoodAnot Verification", "Please click on the link : " + "http://localhost:51248/Verify.aspx?code=" + verificationKey + " to verify your email")
        Catch ex As Exception
        End Try
    End Sub

    Protected Sub btnFollowOutlet_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnFollowOutlet.Click

    End Sub
End Class